package com.boomshake.controller;

import com.boomshake.common.Result;
import com.boomshake.dto.RealNameRequest;
import com.boomshake.dto.UpdateUserRequest;
import com.boomshake.dto.WeChatLoginRequest;
import com.boomshake.service.UserService;
import com.boomshake.utils.JwtUtil;
import com.boomshake.vo.LoginResponseVO;
import com.boomshake.vo.UserInfoVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

/**
 * 用户Controller
 *
 * @author BoomShake
 * @date 2024-12-15
 */
@Slf4j
@RestController
@RequestMapping("/user")
@CrossOrigin(origins = {"http://localhost:5173", "http://localhost:5174", "http://127.0.0.1:5173", "http://127.0.0.1:5174"}, allowCredentials = "true", maxAge = 3600)
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private JwtUtil jwtUtil;

    /**
     * 微信登录
     */
    @PostMapping("/wechat-login")
    public Result<LoginResponseVO> wechatLogin(@Valid @RequestBody WeChatLoginRequest request) {
        try {
            log.info("用户微信登录，code: {}", request.getCode());
            LoginResponseVO response = userService.wechatLogin(request);
            return Result.success("登录成功", response);
        } catch (Exception e) {
            log.error("微信登录失败", e);
            return Result.error("登录失败：" + e.getMessage());
        }
    }

    /**
     * 获取用户信息
     */
    @GetMapping("/info")
    public Result<UserInfoVO> getUserInfo(HttpServletRequest request) {
        try {
            Long userId = getCurrentUserId(request);
            UserInfoVO userInfo = userService.getUserInfo(userId);
            return Result.success(userInfo);
        } catch (Exception e) {
            log.error("获取用户信息失败", e);
            return Result.error("获取用户信息失败：" + e.getMessage());
        }
    }

    /**
     * 提交实名认证
     */
    @PostMapping("/real-name")
    public Result<?> submitRealNameAuth(@Valid @RequestBody RealNameRequest request, 
                                          HttpServletRequest httpRequest) {
        try {
            Long userId = getCurrentUserId(httpRequest);
            log.info("用户{}提交实名认证", userId);
            boolean success = userService.submitRealNameAuth(userId, request);
            
            if (success) {
                return Result.success();
            } else {
                return Result.error("实名认证提交失败");
            }
        } catch (Exception e) {
            log.error("实名认证提交失败", e);
            return Result.error("实名认证提交失败：" + e.getMessage());
        }
    }

    /**
     * 更新个人资料
     */
    @PutMapping("/profile")
    public Result<?> updateProfile(@Valid @RequestBody UpdateUserRequest request, 
                                     HttpServletRequest httpRequest) {
        try {
            Long userId = getCurrentUserId(httpRequest);
            log.info("用户{}更新个人资料", userId);
            boolean success = userService.updateProfile(userId, request);
            
            if (success) {
                return Result.success();
            } else {
                return Result.error("个人资料更新失败");
            }
        } catch (Exception e) {
            log.error("个人资料更新失败", e);
            return Result.error("个人资料更新失败：" + e.getMessage());
        }
    }

    /**
     * 从请求中获取当前用户ID
     */
    private Long getCurrentUserId(HttpServletRequest request) {
        String authHeader = request.getHeader("Authorization");
        String token = jwtUtil.getTokenFromHeader(authHeader);
        
        if (token == null || !jwtUtil.validateToken(token)) {
            throw new RuntimeException("token无效");
        }
        
        return jwtUtil.getUserIdFromToken(token);
    }
} 